import HandleBtn from '@/components/HandleBar/btn';
import type { ActionType, ProColumns, ProFormInstance } from '@/components/Pro/';
import {
  ModalForm,
  ProFormDigit,
  ProFormRadio,
  ProFormSelect,
  ProFormText,
  ProTable,
} from '@/components/Pro/';
import { deviceManagerControllerGetDeviceModelList } from '@/services/ess/deviceManager';
import {
  stationTrmControllerAddTrm as add,
  stationTrmControllerBatchRemove as remove,
  stationTrmControllerBind as bind,
  stationTrmControllerDownloadExcel as downloadFile,
  stationTrmControllerEditTrm as edit,
  stationTrmControllerList as getList,
  stationTrmControllerUnbind as unbind,
  stationTrmControllerUploadExcel as uploadFile,
} from '@/services/ess/stationTrm';
import { DATABASE_TYPE_ENUM, fetchDictInfo } from '@/utils';
import { downloadFetch } from '@/utils/downloadFile';
import type { UploadProps } from 'antd';
import { message, Modal, Space, Upload } from 'antd';
import React, { forwardRef, useEffect, useImperativeHandle, useRef, useState } from 'react';
import { useIntl } from 'umi';
import Styles from './../index.less';

interface DeviceModelVO {
  deviceId: number;
  deviceModelName: string;
}

const { confirm } = Modal;

type ToolBarProps = {
  tableRef: React.MutableRefObject<null>;
};
export const ArchivesToolBarRender: React.FC<ToolBarProps> = ({ tableRef }) => {
  const intl = useIntl();
  const uploadProps: UploadProps = {
    name: 'file',
    multiple: true,
    showUploadList: false,
    customRequest: async (info) => {
      const form = new FormData();
      form.append('file', info.file);
      const res = await uploadFile(form, { ingoreErrorMsg: true });
      if (res?.success) {
        message.success(`${info.file.name} 文件导入成功`);
        tableRef?.current?.actionRef?.current?.reloadAndRest?.();
        return;
      }
      const msg = res?.message;
      message.error(`${info.file.name} 文件导入失败 ${msg ? ',' + msg : ''}`);
    },
  };

  return (
    <>
      <HandleBtn
        handleType="add"
        key="add"
        onClick={() => {
          tableRef?.current?.add();
        }}
      >
        {intl.formatMessage({ id: 'systemManagement.generalProcedure.new' })}
      </HandleBtn>
      <Upload key="import" {...uploadProps}>
        <HandleBtn handleType="import">
          {' '}
          {intl.formatMessage({ id: 'systemManagement.generalProcedure.import' })}
        </HandleBtn>
      </Upload>
      <HandleBtn
        handleType="export"
        key="export"
        onClick={() => {
          downloadFetch(downloadFile, tableRef?.current?.getFormData());
        }}
      >
        {intl.formatMessage({ id: 'systemManagement.generalProcedure.export' })}
      </HandleBtn>
      <HandleBtn
        onClick={() => {
          tableRef?.current?.delete();
        }}
        handleType="delete"
        key="delete"
      >
        {intl.formatMessage({ id: 'systemManagement.generalProcedure.batchDelete' })}
      </HandleBtn>
    </>
  );
};

/**
 * @zh-CN 添加节点
 * @param fields
 */
const handleAdd = async (fields: API.StationTrmReq) => {
  try {
    const res = await add({
      ...fields,
    });
    if (res.success) {
      message.success('添加成功');
      return true;
    }
    return false;
  } catch (error) {
    message.error('添加失败，请稍后重试!');
    return false;
  }
};

/**
 * @zh-CN 编辑节点
 * @param fields
 */
const handleEdit = async (fields: API.StationTrmReq) => {
  try {
    const res = await edit({
      ...fields,
    });
    if (res.success) {
      message.success('编辑成功');
      return true;
    }
    return false;
  } catch (error) {
    message.error('编辑失败，请稍后重试!');
    return false;
  }
};

/**
 * @zh-CN 删除节点
 * @param selectedRows
 */
const handleRemove = async (selectedRows: API.StationInfo[]) => {
  if (!selectedRows) return true;
  try {
    const ids = selectedRows.map((row) => row.id);
    const res = await remove(ids);
    if (res.success) {
      message.success('删除成功');
      return true;
    }
    return false;
  } catch (error) {
    message.error('删除失败，请稍后重试！');
    return false;
  }
};

/**
 * @zh-CN 绑定出厂设备
 * @param trm_id
 * @param fields
 */
const handleBind = async (trm_id: number, fields: API.BindFactoryDeviceDTO) => {
  try {
    const res = await bind(
      { trm_id: trm_id.toString() },
      {
        ...fields,
      },
    );
    if (res.success) {
      message.success('绑定成功');
      return true;
    }
    return false;
  } catch (error) {
    message.error('绑定失败，请稍后重试!');
    return false;
  }
};

/**
 * @zh-CN 解绑出厂设备
 * @param selectedRows
 */
const handleUnbind = async (selectedRows: API.StationTrmReq[]) => {
  if (!selectedRows) return true;
  try {
    const res = await unbind({ trm_id: selectedRows[0].id });
    if (res.success) {
      message.success('解绑成功');
      return true;
    }
    return false;
  } catch (error) {
    message.error('解绑失败，请稍后重试！');
    return false;
  }
};

//fullPage = true 是一个独立表格页面，false是内嵌到其他模块的表格
const TableList = forwardRef(
  (
    {
      id,
      fullPage = true,
      disableEdit = false,
    }: {
      id: string;
      fullPage?: boolean;
      disableEdit?: boolean;
    },
    ref: any,
  ) => {
    const [createModalOpen, handleModalOpen] = useState<boolean>(false);
    const [createBindModalOpen, handleBindModalOpen] = useState<boolean>(false);

    const actionRef = useRef<ActionType>();
    const formRef = useRef<ProFormInstance>();
    const [currentRow, setCurrentRow] = useState<API.StationTrmReq>({});
    const [bindRow] = useState<API.BindFactoryDeviceDTO>({});
    const [selectedRowsState, setSelectedRows] = useState<API.StationTrmReq[]>([]);
    const [disabled, setDisabled] = useState(false);
    const intl = useIntl();

    const deleteRow = (rows: API.StationTrmReq[] = selectedRowsState) => {
      if (rows?.length < 1) {
        message.warning(intl.formatMessage({ id: 'global.leastOne' }));
        return;
      }

      if (disabled) return;
      setDisabled(true);

      confirm({
        title: intl.formatMessage({ id: 'systemManagement.supplementary.prompt' }),
        content: '数据删除后将不可恢复，是否删除？',
        onOk: async () => {
          const res = await handleRemove(rows);
          if (res) {
            setSelectedRows([]);
            actionRef.current?.reloadAndRest?.();
          }
        },
        afterClose: () => {
          setDisabled(false);
        },
      });
    };

    const unbindRow = (rows: API.StationTrmReq[] = selectedRowsState) => {
      if (rows?.length < 1) {
        message.warning(intl.formatMessage({ id: 'global.leastOne' }));
        return;
      }

      if (disabled) return;
      setDisabled(true);

      confirm({
        title: intl.formatMessage({
          id: 'systemManagement.supplementary.doYouWantToUnbindFactoryDevice',
        }),
        content: '设备解绑后将不可恢复，是否解绑？',
        onOk: async () => {
          const res = await handleUnbind(rows);
          if (res) {
            setSelectedRows([]);
            actionRef.current?.reloadAndRest?.();
          }
        },
        afterClose: () => {
          setDisabled(false);
        },
      });
    };

    const [deviceModelList, setDeviceModelList] = useState<DeviceModelVO[]>([]);
    const fetchDeviceModelList = async (deviceType: number) => {
      try {
        const result = await deviceManagerControllerGetDeviceModelList({ deviceType });
        setDeviceModelList(result.data || []);
      } catch (error) {
        console.error(intl.formatMessage({ id: 'siteManage.getDeviceModelFail' }), error);
        setDeviceModelList([]);
      }
    };

    useImperativeHandle(ref, () => ({
      add: () => {
        setCurrentRow({});
        handleModalOpen(true);
      },
      delete: () => {
        deleteRow();
      },
      getFormData: () => {
        return { ...formRef?.current?.getFieldsFormatValue(), stationId: id };
      },
      actionRef: actionRef,
    }));

    const columns: ProColumns<API.StationTrmReq>[] = [
      {
        title: intl.formatMessage({ id: 'systemManagement.generalProcedure.SN' }),
        hideInSearch: true,
        dataIndex: 'pageIndex',
      },
      {
        title: intl.formatMessage({ id: 'systemManagement.siteAdministrationMenu.deviceName' }),
        dataIndex: 'name',
        hideInSearch: true,
      },
      {
        title: intl.formatMessage({ id: 'systemManagement.deviceManagementMenu.DeviceType' }),
        dataIndex: 'type',
        request: () => fetchDictInfo(DATABASE_TYPE_ENUM.DEVICE_TYPE),
        valueType: 'select',
        hideInSearch: true,
      },
      {
        title: intl.formatMessage({ id: 'systemManagement.siteAdministrationMenu.agreement' }),
        dataIndex: 'protocolType',
        request: () => fetchDictInfo(DATABASE_TYPE_ENUM.COMMUNICATION_PROTOCOL),
        valueType: 'select',
        hideInSearch: true,
      },
      {
        title: intl.formatMessage({
          id: 'systemManagement.siteAdministrationMenu.communicationAddress',
        }),
        dataIndex: 'address',
        hideInSearch: true,
      },
      {
        title: intl.formatMessage({ id: 'systemManagement.deviceManagementMenu.status' }),
        dataIndex: 'status',
        valueEnum: {
          0: {
            text: intl.formatMessage({ id: 'systemManagement.supplementary.debug' }),
            status: 'Default',
          },
          1: {
            text: intl.formatMessage({ id: 'systemManagement.supplementary.running' }),
            status: 'Processing',
          },
        },
        hideInSearch: true,
      },
      {
        dataIndex: 'search',
        fieldProps: () => {
          return {
            style: { width: 400 },
            placeholder: intl.formatMessage({ id: 'systemManagement.requiredFields.searchDevice' }),
          };
        },
        hideInTable: true,
      },
    ];
    if (!disableEdit) {
      columns.push({
        title: intl.formatMessage({ id: 'systemManagement.generalProcedure.operation' }),
        dataIndex: 'option',
        valueType: 'option',
        render: (_, record) => (
          <Space>
            <a
              key="edit"
              onClick={() => {
                handleModalOpen(true);
                setCurrentRow(record);
              }}
            >
              {intl.formatMessage({ id: 'systemManagement.generalProcedure.edit' })}
            </a>
            {record.factorySn === null ? (
              <a
                key="bind"
                onClick={() => {
                  fetchDeviceModelList(record.type);
                  handleBindModalOpen(true);
                  setCurrentRow(record);
                }}
              >
                {intl.formatMessage({ id: 'systemManagement.generalProcedure.bind' })}
              </a>
            ) : (
              <a key="unbind" onClick={() => unbindRow([record])}>
                {intl.formatMessage({ id: 'systemManagement.generalProcedure.unbind' })}
              </a>
            )}
            <a key="delete" className="global-del-color" onClick={() => deleteRow([record])}>
              {intl.formatMessage({ id: 'systemManagement.generalProcedure.delete' })}
            </a>
          </Space>
        ),
      });
    }

    // 将 selectedProtocol 改为 selectedDeviceType
    const [selectedDeviceType, setSelectedDeviceType] = useState<number>(currentRow?.type);

    // 更新 useEffect，监听 currentRow 中的设备类型变化
    useEffect(() => {
      setSelectedDeviceType(currentRow?.type);
    }, [currentRow]);

    return (
      <>
        <ProTable<API.StationTrmReq, API.PageParams>
          headerTitle={
            fullPage &&
            intl.formatMessage({ id: 'systemManagement.siteAdministrationMenu.collectionArchive' })
          }
          actionRef={actionRef}
          formRef={formRef}
          rowKey="id"
          toolBarRender={fullPage ? () => <ArchivesToolBarRender tableRef={ref} /> : false}
          toolbar={{
            settings: [],
          }}
          params={{
            stationId: id,
          }}
          request={getList}
          columns={columns}
          rowSelection={
            !disableEdit && {
              onChange: (_, selectedRows) => {
                setSelectedRows(selectedRows);
              },
            }
          }
          search={{
            layoutType: 'Form',
            layout: 'inline',
            style: fullPage ? { padding: 30 } : { padding: '10px 0 30px' },
            submitter: {
              searchConfig: {
                submitText: intl.formatMessage({
                  id: 'systemManagement.generalProcedure.search',
                }),
              },
              resetButtonProps: false,
            },
          }}
          className={`global-secondary-table ${!fullPage && Styles.resetForm}`}
        />
        <ModalForm
          modalProps={{
            destroyOnClose: true,
          }}
          // Update initialValues to include meterCount and cabinetCount
          initialValues={{
            ...currentRow,
            status: currentRow?.status ?? 0,
            meterCount: currentRow?.meterCount,
            cabinetCount: currentRow?.cabinetCount,
          }}
          title={
            currentRow?.id
              ? intl.formatMessage({
                  id: 'systemManagement.siteAdministrationMenu.editCollectionDevice',
                })
              : intl.formatMessage({
                  id: 'systemManagement.siteAdministrationMenu.addCollectionDevice',
                })
          }
          width="730px"
          colProps={{ md: 12 }}
          open={createModalOpen}
          onOpenChange={handleModalOpen}
          onFinish={async (value) => {
            let success;
            value.stationId = id;
            if (currentRow?.id) {
              success = await handleEdit({ ...currentRow, ...value } as API.StationTrmReq);
            } else {
              success = await handleAdd(value as API.StationTrmReq);
            }
            if (success) {
              handleModalOpen(false);
              if (actionRef.current) {
                actionRef.current.reload();
              }
            }
          }}
        >
          <ProFormText
            name="name"
            label={intl.formatMessage({ id: 'systemManagement.siteAdministrationMenu.deviceName' })}
            rules={[
              {
                required: true,
                message: intl.formatMessage({ id: 'systemManagement.requiredFields.deviceName' }),
              },
            ]}
            fieldProps={{
              maxLength: 30,
            }}
          />
          <ProFormSelect
            name="type"
            label={intl.formatMessage({ id: 'systemManagement.deviceManagementMenu.DeviceType' })}
            request={() => fetchDictInfo(DATABASE_TYPE_ENUM.DEVICE_TYPE, true)}
            rules={[
              {
                required: true,
                message: intl.formatMessage({ id: 'systemManagement.requiredFields.deviceType' }),
              },
            ]}
            fieldProps={{
              onChange: (value) => setSelectedDeviceType(value),
            }}
          />
          <ProFormSelect
            name="protocolType"
            label={intl.formatMessage({
              id: 'systemManagement.siteAdministrationMenu.communicationProtocol',
            })}
            rules={[
              {
                required: true,
                message: intl.formatMessage({
                  id: 'systemManagement.requiredFields.communicationProtocol',
                }),
              },
            ]}
            request={() => fetchDictInfo(DATABASE_TYPE_ENUM.COMMUNICATION_PROTOCOL, true)}
          />

          {/* 更新条件，只在设备类型为储能柜(1)时显示 */}
          {selectedDeviceType === 1 && (
            <>
              <ProFormDigit
                name="meterCount"
                label={intl.formatMessage({ id: 'systemManagement.requiredFields.meterCount' })}
                rules={[
                  {
                    required: true,
                    message: intl.formatMessage({
                      id: 'systemManagement.requiredFields.meterCountTips',
                    }),
                  },
                ]}
                min={0}
                fieldProps={{ precision: 0 }}
              />
              <ProFormDigit
                name="cabinetCount"
                label={intl.formatMessage({ id: 'systemManagement.requiredFields.cabinetCount' })}
                rules={[
                  {
                    required: true,
                    message: intl.formatMessage({
                      id: 'systemManagement.requiredFields.cabinetCountTips',
                    }),
                  },
                ]}
                min={0}
                fieldProps={{ precision: 0 }}
              />
            </>
          )}

          <ProFormText
            name="address"
            label={intl.formatMessage({
              id: 'systemManagement.siteAdministrationMenu.communicationAddress',
            })}
            colProps={{ md: 24 }}
            rules={[
              {
                required: true,
                message: intl.formatMessage({
                  id: 'systemManagement.requiredFields.communicationAddress',
                }),
              },
            ]}
          />
          <ProFormRadio.Group
            label={intl.formatMessage({ id: 'systemManagement.deviceManagementMenu.status' })}
            name="status"
            initialValue={intl.formatMessage({
              id: 'systemManagement.supplementary.debug',
            })}
            rules={[
              {
                required: true,
                message: intl.formatMessage({ id: 'systemManagement.requiredFields.status' }),
              },
            ]}
            options={[
              {
                label: intl.formatMessage({ id: 'systemManagement.supplementary.running' }),
                value: 1,
              },
              {
                label: intl.formatMessage({ id: 'systemManagement.supplementary.debug' }),
                value: 0,
              },
            ]}
          />
        </ModalForm>
        <ModalForm
          modalProps={{
            destroyOnClose: true,
          }}
          initialValues={{ ...bindRow, status: 0 }}
          title={intl.formatMessage({
            id: 'systemManagement.siteAdministrationMenu.bindFactoryDevice',
          })}
          width="730px"
          colProps={{ md: 12 }}
          open={createBindModalOpen}
          onOpenChange={handleBindModalOpen}
          onFinish={async (value) => {
            value.trm_id = id;
            let success = await handleBind(currentRow.id, {
              ...bindRow,
              ...value,
            } as API.BindFactoryDeviceDTO);
            if (success) {
              handleBindModalOpen(false);
              if (actionRef.current) {
                actionRef.current.reload();
              }
            }
          }}
        >
          <ProFormSelect
            name="deviceModelId"
            label={intl.formatMessage({
              id: 'systemManagement.deviceManagementMenu.Devicemodel',
            })}
            rules={[
              {
                required: true,
                message: intl.formatMessage({
                  id: 'systemManagement.requiredFields.Devicemodel',
                }),
              },
            ]}
            options={deviceModelList.map((model) => ({
              label: model.deviceModelName,
              value: model.deviceId,
            }))}
          />
          <ProFormText
            name="sn"
            label={intl.formatMessage({ id: 'systemManagement.siteAdministrationMenu.factorySn' })}
            rules={[
              {
                required: true,
                message: intl.formatMessage({ id: 'systemManagement.requiredFields.factorySn' }),
              },
            ]}
            fieldProps={{
              maxLength: 30,
            }}
          />
        </ModalForm>
      </>
    );
  },
);

export default TableList;
